import instance from '@/utils/request.js'
import store from '@/store'
// 所有与用户有关的函数
/*
 * 获取用户的频道列表
 * @param
 * @return Promise
 *
*/
export const getUserchannels = async () => {
  // 如果没有token获取本地存储的channels
  if (!store.state.user.token) {
    const channels = JSON.parse(window.localStorage.getItem('channels') || '[]')
    if (channels.length) {
      return channels
    }
  }

  const channels = await instance({
    url: 'user/channels'
  })
  return channels
}
/*
 * 获取所有的的频道列表
 * @param
 * @return Promise
 *
*/
export const getAllchannels = () => {
  return instance({
    url: 'channels'
  })
}
/*
 * 获取新闻推荐
 * @param {channel_id} string
 * @param {timestamp} string
 * @return Promise
 *
*/
/* eslint-disable camelcase */
export const getArticles = (channel_id, timestamp) => {
  return instance({
    url: 'articles',
    params: {
      channel_id,
      timestamp
    }
  })
}
/**
 * 增加我的频道
 * @param channels : 所有的频道新
 * @returns Promise
 */

export const addMyChannels = (channels) => {
  if (!store.state.user.token) {
    // 1. 获取本地的存储
    const localData = JSON.parse(window.localStorage.getItem('channels') || '[]')
    // 2. 组装数据
    const { id, name } = channels[channels.length - 1]
    // 3. push到localData
    localData.push({ id, name })
    // 4.存储到本地
    return window.localStorage.setItem('channels', JSON.stringify(localData))
  }
  return instance({
    url: 'user/channels',
    method: 'PUT',
    data: {
      channels
    }
  })
}
/*
 * 删除我的频道
 * @param {channel_id} string
 * @return Promise
 *
*/
export const delMyChannel = (id) => {
  return instance({
    url: 'user/channels/' + id,
    method: 'delete'
  })
}
